<?php

abstract class Kd_Model_Collection_Strong extends Kd_Model_Collection_Base {

    private $_itemClass = NULL;

    public function __construct() {
        parent::__construct();
    }

    public function getItemClass() {
        return $this->_itemClass;
    }

    protected function setItemClass($value) {
        $this->_itemClass = $value;
        return $this;
    }

    public function hasItem($entity) {
        foreach ($this as $item) {
            if ($item->equal($entity)) {
                return TRUE;
            }
        }
        return FALSE;
    }

    public function getItemById($id) {
        foreach ($this as $item) {
            if ($item->equalId($id)){
                return $item;
            }
        }
        return NULL;
    }

    public function removeItemById($id) {
        $ids = Kd_Util_Array::pack($id);
        foreach ($ids as $itemId) {
            for ($i = 0; $i < count($this); $i++) {
                $item = $this[$i];
                if (strcmp($item->getIdValue(), $itemId) == 0) {
                    $this->offsetUnset($i);
                    break;
                }
            }
        }
        return $this;
    }

    public function findItems(array $conditions) {
        $this->reset();
        $result = array();
        foreach ($this as $item) {
            $isMatch = TRUE;
            foreach ($conditions as $property => $value) {
                if ($item[$property] != $value) {
                    $isMatch = FALSE;
                    break;
                }
            }
            $result[] = $item;
        }
        return $result;
    }

    public function fill(array $data) {
        $class = $this->getItemClass();
        foreach ($data as $row) {
            $item = new $class();
            $item->fill($row)->markNoChanged();
            $this->append($item);
        }
        return $this;
    }

}